package com.learn.netty.memory;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 通过unsafe类来直接操作内存
 * <p>
 * -XX:MaxDirectMemorySize:指定堆外内存的上限大小，当堆外内存的大小超过该阈值时，
 * 就会触发一次 Full GC 进行清理回收，如果在 Full GC 之后还是无法满足堆外内存的
 * 分配，那么程序将会抛出 OOM 异常。
 * </p>
 */
public class UnsafeTest {

    private static Unsafe unsafe = null;

    static {
        try {
            Field getUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            getUnsafe.setAccessible(true);
            unsafe = (Unsafe) getUnsafe.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 分配 10m 堆外内存
        System.out.println("start allocate memory address");
        long address = unsafe.allocateMemory(10 * 1024 * 1024);
        System.out.println("end allocate memory address");
        System.out.println(address);
        // 必须自己手动释放，否则会造成内存泄露
        System.out.println("start free memory address");
        unsafe.freeMemory(address);
        System.out.println("end free memory address");
    }


}
